#!/usr/bin/env python3
"""
清理数据库中的无效头像引用
将引用不存在文件的头像字段设为 NULL
"""
import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from app.core.database import SessionLocal
from app.models.user import User
from app.models.team import Team, TeamMember
from app.services.minio_service import MinIOService
from app.core.config import settings

def check_file_exists(file_url):
    """检查文件是否在 MinIO 中存在"""
    if not file_url or '/football/' not in file_url:
        return False
    
    try:
        # 提取文件路径
        file_path = file_url.split('/football/')[-1]
        
        # 检查文件是否存在
        minio_service = MinIOService()
        try:
            minio_service.client.stat_object(settings.MINIO_BUCKET, file_path)
            return True
        except:
            return False
    except:
        return False

def clear_invalid_avatars():
    """清理无效的头像引用"""
    db = SessionLocal()
    
    try:
        print("🔧 开始清理无效头像引用...\n")
        
        total_fixed = 0
        
        # 1. 清理用户头像
        print("👤 检查用户头像...")
        users = db.query(User).all()
        user_fixed = 0
        
        for user in users:
            if user.avatar:
                if not check_file_exists(user.avatar):
                    print(f"  ❌ 用户 {user.nick_name} 的头像无效: {user.avatar}")
                    user.avatar = None
                    user_fixed += 1
                else:
                    print(f"  ✅ 用户 {user.nick_name} 的头像有效")
        
        if user_fixed > 0:
            print(f"  清空了 {user_fixed} 个用户头像\n")
        else:
            print(f"  所有用户头像都有效\n")
        
        # 2. 清理球队Logo
        print("🏃 检查球队Logo...")
        teams = db.query(Team).all()
        team_fixed = 0
        
        for team in teams:
            if team.logo:
                if not check_file_exists(team.logo):
                    print(f"  ❌ 球队 {team.name} 的Logo无效: {team.logo}")
                    team.logo = None
                    team_fixed += 1
                else:
                    print(f"  ✅ 球队 {team.name} 的Logo有效")
        
        if team_fixed > 0:
            print(f"  清空了 {team_fixed} 个球队Logo\n")
        else:
            print(f"  所有球队Logo都有效\n")
        
        # 3. 清理球队成员头像
        print("👥 检查球队成员头像...")
        members = db.query(TeamMember).all()
        member_fixed = 0
        
        for member in members:
            if member.avatar:
                if not check_file_exists(member.avatar):
                    print(f"  ❌ 成员 {member.user_name} 的头像无效: {member.avatar}")
                    member.avatar = None
                    member_fixed += 1
                else:
                    print(f"  ✅ 成员 {member.user_name} 的头像有效")
        
        if member_fixed > 0:
            print(f"  清空了 {member_fixed} 个成员头像\n")
        else:
            print(f"  所有成员头像都有效\n")
        
        # 提交更改
        total_fixed = user_fixed + team_fixed + member_fixed
        
        if total_fixed > 0:
            db.commit()
            print("=" * 60)
            print(f"✅ 清理完成！总共清空了 {total_fixed} 个无效引用")
            print("=" * 60)
            print("\n📝 后续操作：")
            print("  1. 用户可以在个人资料页重新上传头像")
            print("  2. 队长可以在球队编辑页重新上传Logo")
            print("  3. 新上传的图片会使用正确的 HTTPS URL")
        else:
            print("=" * 60)
            print("🎉 没有发现无效引用，所有图片都正常！")
            print("=" * 60)
    
    except Exception as e:
        print(f"\n❌ 清理失败: {e}")
        db.rollback()
        raise
    
    finally:
        db.close()

if __name__ == "__main__":
    try:
        clear_invalid_avatars()
    except Exception as e:
        print(f"\n❌ 执行失败: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

